package routes

import (
	"net/http"

	"sysu-giep/internal/api/handlers"
	"sysu-giep/internal/api/middleware"
	"sysu-giep/internal/config"
	"sysu-giep/internal/database"
	"sysu-giep/internal/database/models"
	"sysu-giep/internal/service"
	"sysu-giep/pkg/auth"

	"github.com/gin-gonic/gin"
)

// SetupRoutes 设置RESTful API路由
func SetupRoutes(engine *gin.Engine, cfg *config.Config, jwtManager *auth.JWTManager, backupHandler *handlers.BackupHandler) {
	// 将配置存储到Gin上下文中，供处理器使用
	engine.Use(func(c *gin.Context) {
		c.Set("config", cfg)
		c.Next()
	})

	// 初始化私聊服务
	privateChatService := service.NewPrivateChatService(database.GetDB())
	privateChatHandler := handlers.NewPrivateChatHandler(privateChatService)
	wsPrivateChatHandler := handlers.NewWebSocketPrivateChatHandler(privateChatService, jwtManager)
	// 根路径 - 提供API信息
	engine.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message":  "中山大学研究生院校企对接平台 API",
			"version":  cfg.App.Version,
			"docs":     "/api/v1/health",
			"api_base": "/api/v1",
		})
	})

	// API版本组
	v1 := engine.Group("/api/v1")

	// 健康检查
	v1.GET("/health", handlers.HealthCheck)

	// 认证相关路由
	authGroup := v1.Group("/auth")
	{
		authGroup.POST("/register", handlers.Register)                          // 用户注册
		authGroup.POST("/login", handlers.Login)                                // 用户登录
		authGroup.POST("/refresh", middleware.JWTAuth(), handlers.RefreshToken) // 刷新令牌
		authGroup.POST("/logout", middleware.JWTAuth(), handlers.Logout)        // 用户登出
	}

	// 邮箱相关路由
	emailGroup := v1.Group("/email")
	{
		emailGroup.POST("/send", handlers.SendEmail)             // 发送邮件
		emailGroup.POST("/validate", handlers.ValidateEmailCode) // 验证邮箱验证码
	}

	// 用户相关路由 - RESTful风格
	userGroup := v1.Group("/users")
	userGroup.Use(middleware.JWTAuth())
	{
		userGroup.GET("/me", handlers.GetProfile)              // 获取当前用户信息
		userGroup.PUT("/me", handlers.UpdateProfile)           // 更新当前用户信息
		userGroup.PUT("/me/password", handlers.ChangePassword) // 修改密码
		userGroup.GET("/:id", handlers.GetUserByID)            // 根据ID获取用户信息
	}

	// 课题相关路由 - RESTful风格
	projectGroup := v1.Group("/projects")
	{
		// 公开接口
		projectGroup.GET("", handlers.GetProjects)        // 获取课题列表
		projectGroup.GET("/:id", handlers.GetProjectByID) // 根据ID获取课题详情

		projectGroup.GET("/search", handlers.SearchProjects)           // 搜索课题
		projectGroup.GET("/categories", handlers.GetProjectCategories) // 获取课题分类

		// 需要认证的接口
		authProjectGroup := projectGroup.Group("")
		authProjectGroup.Use(middleware.JWTAuth())
		{
			authProjectGroup.POST("", middleware.RequireRole(models.RoleEnterprise), handlers.CreateProject)                                         // 创建课题
			authProjectGroup.PUT("/:id", middleware.RequireRole(models.RoleEnterprise), handlers.UpdateProject)                                      // 更新课题
			authProjectGroup.DELETE("/:id", middleware.RequireRole(models.RoleEnterprise), handlers.DeleteProject)                                   // 删除课题
			authProjectGroup.GET("/my", middleware.RequireRole(models.RoleEnterprise, models.RoleTutor, models.RoleStudent), handlers.GetMyProjects) // 获取我的课题
			authProjectGroup.POST("/:id/applications", middleware.RequireRole(models.RoleTutor, models.RoleStudent), handlers.ApplyProject)          // 申请课题

			authProjectGroup.POST("/:id/favorite", middleware.RequireRole(models.RoleTutor, models.RoleStudent), handlers.FavoriteProject)                  // 收藏课题
			authProjectGroup.DELETE("/:id/favorite", middleware.RequireRole(models.RoleTutor, models.RoleStudent), handlers.UnfavoriteProject)              // 取消收藏
			authProjectGroup.GET("/favorites", middleware.RequireRole(models.RoleTutor, models.RoleStudent), handlers.GetFavoriteProjects)                  // 获取收藏的课题
			authProjectGroup.POST("/:id/share", middleware.RequireRole(models.RoleTutor, models.RoleStudent, models.RoleEnterprise), handlers.ShareProject) // 分享课题

			// 推荐相关接口
			authProjectGroup.GET("/recommendations", middleware.RequireRole(models.RoleStudent, models.RoleTutor), handlers.GetRecommendedProjects) // 获取推荐课题
		}
	}

	// 申请相关路由 - RESTful风格
	applicationGroup := v1.Group("/applications")
	applicationGroup.Use(middleware.JWTAuth())
	{
		applicationGroup.GET("", handlers.GetApplications)
		applicationGroup.POST("", handlers.CreateApplication)                                                                // 创建申请
		applicationGroup.GET("/:id", handlers.GetApplicationByID)                                                            // 根据ID获取申请详情
		applicationGroup.PUT("/:id/status", middleware.RequireRole(models.RoleEnterprise), handlers.UpdateApplicationStatus) // 更新申请状态
		applicationGroup.DELETE("/:id", handlers.WithdrawApplication)                                                        // 撤回申请
		applicationGroup.GET("/my", handlers.GetMyApplications)                                                              // 获取我的申请
	}

	// 匹配相关路由 - RESTful风格
	matchGroup := v1.Group("/matches")
	matchGroup.Use(middleware.JWTAuth())
	{
		matchGroup.GET("", handlers.GetMatches)                // 获取匹配列表
		matchGroup.GET("/my", handlers.GetMyMatches)           // 获取我的匹配
		matchGroup.POST("/:id/confirm", handlers.ConfirmMatch) // 确认匹配
	}

	// 通知相关路由 - RESTful风格
	notificationGroup := v1.Group("/notifications")
	notificationGroup.Use(middleware.JWTAuth())
	{
		notificationGroup.GET("", handlers.GetNotifications)                        // 获取通知列表
		notificationGroup.GET("/unread/count", handlers.GetUnreadNotificationCount) // 获取未读通知数量
		notificationGroup.PUT("/:id/read", handlers.MarkNotificationAsRead)         // 标记通知为已读
	}

	// 管理员路由 - RESTful风格
	adminGroup := v1.Group("/admin")
	adminGroup.Use(middleware.JWTAuth(), middleware.RequireRole(models.RoleAdmin))
	{
		// 用户管理
		adminGroup.GET("/users", handlers.AdminGetUsers)                    // 获取所有用户
		adminGroup.PUT("/users/:id/status", handlers.AdminUpdateUserStatus) // 更新用户状态

		// 课题管理
		adminGroup.GET("/projects", handlers.AdminGetProjects)                    // 获取所有课题
		adminGroup.PUT("/projects/:id/status", handlers.AdminUpdateProjectStatus) // 更新课题状态

		// 申请管理
		adminGroup.GET("/applications", handlers.AdminGetApplications)                    // 获取所有申请
		adminGroup.PUT("/applications/:id/status", handlers.AdminUpdateApplicationStatus) // 更新申请状态

		// 手动匹配管理
		adminGroup.POST("/matches", handlers.AdminManualMatch)                            // 手动匹配
		adminGroup.GET("/matches", handlers.AdminGetMatches)                              // 获取所有匹配记录
		adminGroup.GET("/matches/candidates", handlers.AdminGetMatchCandidates)           // 获取匹配候选者
		adminGroup.GET("/matches/project-candidates", handlers.AdminGetProjectCandidates) // 获取课题候选者
		adminGroup.DELETE("/matches/:id", handlers.AdminRemoveMatch)                      // 移除匹配

		// 统计信息
		adminGroup.GET("/statistics", handlers.AdminGetStatistics)           // 获取统计信息
		adminGroup.GET("/statistics/export", handlers.AdminExportStatistics) // 导出统计信息

		// 仪表盘接口
		adminGroup.GET("/dashboard/stats", handlers.AdminGetDashboardStats)           // 获取仪表盘统计数据
		adminGroup.GET("/dashboard/user-chart", handlers.AdminGetUserChartData)       // 获取用户图表数据
		adminGroup.GET("/dashboard/project-chart", handlers.AdminGetProjectChartData) // 获取课题图表数据

		// 定时任务管理
		adminGroup.GET("/tasks/status", func(c *gin.Context) {
			if backupHandler != nil {
				backupHandler.GetTaskStatus(c)
			} else {
				c.JSON(http.StatusServiceUnavailable, gin.H{"error": "备份服务未初始化"})
			}
		}) // 获取任务状态
		adminGroup.POST("/tasks/:task_id/start", func(c *gin.Context) {
			if backupHandler != nil {
				backupHandler.StartTask(c)
			} else {
				c.JSON(http.StatusServiceUnavailable, gin.H{"error": "备份服务未初始化"})
			}
		}) // 启动任务
		adminGroup.POST("/tasks/:task_id/stop", func(c *gin.Context) {
			if backupHandler != nil {
				backupHandler.StopTask(c)
			} else {
				c.JSON(http.StatusServiceUnavailable, gin.H{"error": "备份服务未初始化"})
			}
		}) // 停止任务
		adminGroup.POST("/tasks/:task_id/execute", func(c *gin.Context) {
			if backupHandler != nil {
				backupHandler.ExecuteTask(c)
			} else {
				c.JSON(http.StatusServiceUnavailable, gin.H{"error": "备份服务未初始化"})
			}
		}) // 手动执行任务
		adminGroup.DELETE("/tasks/:task_id", func(c *gin.Context) {
			if backupHandler != nil {
				backupHandler.RemoveTask(c)
			} else {
				c.JSON(http.StatusServiceUnavailable, gin.H{"error": "备份服务未初始化"})
			}
		}) // 移除任务
	}

	// 私聊相关路由 - RESTful风格
	privateChatGroup := v1.Group("/private-chat")
	privateChatGroup.Use(middleware.JWTAuth())
	{
		// 私聊会话管理
		privateChatGroup.GET("/chats", privateChatHandler.GetChats)                  // 获取私聊会话列表
		privateChatGroup.GET("/chats/:partner_id", privateChatHandler.GetChat)       // 获取私聊会话详情
		privateChatGroup.DELETE("/chats/:partner_id", privateChatHandler.DeleteChat) // 删除私聊会话

		// 私聊消息
		privateChatGroup.GET("/chats/:partner_id/messages", privateChatHandler.GetMessages)    // 获取私聊消息
		privateChatGroup.POST("/chats/:partner_id/messages", privateChatHandler.SendMessage)   // 发送私聊消息
		privateChatGroup.PUT("/chats/:partner_id/read", privateChatHandler.MarkMessagesAsRead) // 标记消息为已读

		// 统计信息
		privateChatGroup.GET("/unread-count", privateChatHandler.GetUnreadCount)                       // 获取总未读消息数量
		privateChatGroup.GET("/chats/:partner_id/unread-count", privateChatHandler.GetChatUnreadCount) // 获取与特定用户的未读消息数量

		// 用户搜索和在线状态
		privateChatGroup.GET("/search-users", privateChatHandler.SearchUsers)   // 搜索用户
		privateChatGroup.GET("/online-users", privateChatHandler.GetOnlineUsers) // 获取在线用户列表
	}

	// 兼容前端路径的聊天路由
	chatGroup := v1.Group("/chat")
	chatGroup.Use(middleware.JWTAuth())
	{
		// 直接映射到私聊接口，保持前端API调用不变
		chatGroup.GET("/conversations", privateChatHandler.GetChats)                     // 获取聊天会话列表
		chatGroup.GET("/messages", privateChatHandler.GetMessagesForChatAPI)            // 获取消息（适配器方法）
		chatGroup.POST("/messages", privateChatHandler.SendMessageForChatAPI)           // 发送消息（适配器方法）
		chatGroup.PUT("/messages/read/:user_id", privateChatHandler.MarkMessagesAsReadForChatAPI) // 标记消息为已读（适配器方法）
		chatGroup.GET("/online-users", privateChatHandler.GetOnlineUsers)               // 获取在线用户列表
		chatGroup.GET("/search-users", privateChatHandler.SearchUsers)                 // 搜索用户
		chatGroup.POST("/conversations", privateChatHandler.GetChat)                   // 创建对话（复用获取会话接口）
	}

	// WebSocket私聊路由
	wsGroup := v1.Group("/ws")
	{
		wsGroup.GET("/private-chat", wsPrivateChatHandler.HandleWebSocket) // WebSocket私聊连接
	}

	// 404处理
	engine.NoRoute(handlers.NotFound)
}
